package com.xbzl.cly_demo.handler;

import com.xbzl.cly_demo.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

//    @ExceptionHandler
//    public Result exceptionHandler(Exception ex){
//        log.error("异常信息：{}", ex.getMessage());
//        return Result.error(ex.getMessage());
//    }

    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        //得到错误信息中第三个字符 就是名字 封装到错误中s
        if (message.contains("Duplicate entry")){
            String[] strings = message.split(" ");
            String name = strings[2];
            return Result.error(name + "名字重复");
        }else {
            return Result.error("未知错误");
        }
    }
}
